import React from 'react';
import PageTitle from 'component/page-title/PageTitle.jsx';

import MUtil from 'util/MUtil.jsx';
const mUtil = new MUtil();
import ProductService from 'service/ProductService.jsx';
const productService = new ProductService();
import CategorySelector from 'page/product/index/CategorySelector.jsx';
import FileUploadUtil from 'util/FileUploadUtil.jsx';
import RichEditor from 'util/rich-editor/RichEditor.jsx';

import './category-selector.styl';
import './product-save.styl';
class ProductSave extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      id: this.props.match.params.pid,
      name: '',
      subtitle: '',
      categoryId: 0,
      parentCategoryId: 0,
      subImages: [],
      detail: '',// 富文本
      price: '',
      stock: '',// 库存数
      status: 1,// 为1表示商品在售
      defaultDetail: '',
    };
  }
  // {
  //   uri: "73a448d5-8bfb-42f0-abbb-6485e491c9fb.jpg",
  //   url: "http://img.happymmall.com/73a448d5-8bfb-42f0-abbb-6485e491c9fb.jpg"
  // }

  componentDidMount() {
    if (this.state.id) { // 如果为true，则表明是编辑，否则为添加
      productService.getProduct(this.state.id)
        .then(res => {
          let images = res.data.subImages.split(',');
          res.data.subImages = images.map(imgUri => {
            return {
              uri: imgUri,
              url: res.data.imageHost + imgUri
            }
          });
          res.data.defaultDetail = res.data.detail;
          this.setState(res.data);
          // this.setState({ subImages: res.data.subImages });
        }
          , errMsg => mUtil.errorTips(errMsg));
    }
  }

  /**
   * 品类选择
   * @param {类别Id} categoryId 
   * @param {父类别Id} parentCategoryId 
   */
  onCategoryChange(categoryId, parentCategoryId) {
    this.setState({ categoryId, parentCategoryId });
  }

  /**
   * 图片上传成功
   * @param {成功返回的信息} data
   */
  onUploadSuccess(data) {
    this.state.subImages.push(data);
    this.setState({
      subImages: this.state.subImages
    });
  }

  /**
   * 图片上传失败
   * @param {失败信息} errMsg 
   */
  onUploadError(errMsg) {
    mUtil.errorTips(errMsg);
  }

  /**
   * 删除已经上传的图片
   * @param {*} e 
   */
  onImageDelete(e) {
    let index = parseInt(e.target.getAttribute('index'));
    this.state.subImages.splice(index, 1);
    this.setState({ subImages: this.state.subImages });
  }

  /**
   * 富文本变化回调
   * @param {*} value 
   */
  onDetailValueChange(detail) {

    this.setState({ detail });
  }

  onValueChange(e) {
    let name = e.target.name,
      value = e.target.value;
    this.setState({ [name]: value });
  }
  /**
   * 处理图片
   */
  getSubImagesString() {
    return this.state.subImages.map((image, index) => image.uri).join(',');
  }
  /**
   * 提交表单
   */
  onSubmit() {
    let product = {
      name: this.state.name,
      subtitle: this.state.subtitle,
      subImages: this.getSubImagesString(),
      categoryId: parseInt(this.state.categoryId),
      detail: this.state.detail,
      price: parseInt(this.state.price),
      stock: parseInt(this.state.stock),
      status: this.state.status,
    };
    let productCheckResult = productService.checkProduct(product);
    if (this.state.id)
      product.id = this.state.id;
    if (productCheckResult.status) { // 表单验证通过
      productService.saveProduct(product)
        .then(res => {
          mUtil.successTips(res.data);
          this.props.history.push('/product');
        },
          errMsg => mUtil.errorTips(errMsg));
    } else {
      mUtil.errorTips(productCheckResult.msg);
    }

  }

  render() {
    return (
      <div id="page-wrapper">
        <PageTitle title={this.state.id ? '编辑商品' : '添加商品'} />
        <div className="form-horizontal">
          <div className="form-group">
            <label className="col-md-2 control-label">商品名称</label>
            <div className="col-md-5">
              <input type="text" className="form-control" placeholder="请输入商品名称"
                name="name"
                value={this.state.name}
                onChange={e => this.onValueChange(e)} />
            </div>
          </div>
          <div className="form-group">
            <label className="col-md-2 control-label">商品描述</label>
            <div className="col-md-5">
              <input type="text" className="form-control" placeholder="请输入商品描述"
                name="subtitle"
                value={this.state.subtitle}
                onChange={e => this.onValueChange(e)} />
            </div>
          </div>
          <div className="form-group">
            <label className="col-md-2 control-label">所属分类</label>
            <CategorySelector
              categoryId={this.state.categoryId} parentCategoryId={this.state.parentCategoryId}
              onCategoryChange={(categoryId, parentCategoryId) => this.onCategoryChange(categoryId, parentCategoryId)} />
          </div>
          <div className="form-group">
            <label className="col-md-2 control-label">商品价格</label>
            <div className="col-md-3">
              <div className="input-group">
                <input type="number" className="form-control" placeholder='价格'
                  name="price"
                  value={this.state.price}
                  onChange={e => this.onValueChange(e)} />
                <span className="input-group-addon">元</span>
              </div>
            </div>
          </div>
          <div className="form-group">
            <label className="col-md-2 control-label">商品库存</label>
            <div className="col-md-3">
              <div className="input-group">
                <input type="number" className="form-control" placeholder='库存'
                  name="stock"
                  value={this.state.stock}
                  onChange={e => this.onValueChange(e)} />
                <span className="input-group-addon">件</span>
              </div>
            </div>
          </div>
          <div className="form-group">
            <label className="col-md-2 control-label">商品图片</label>
            <div className="col-md-10">
              {/* 用于上传的图片展示 */}
              {
                this.state.subImages.length ? this.state.subImages
                  .map((image, index) => (
                    <div className="img-con" key={index}>
                      <img src={image.url} className="img" />
                      <i className="fa fa-close" index={index}
                        onClick={e => this.onImageDelete(e)}></i>
                    </div>))
                  : (<div>请上传图片</div>)
              }
            </div>
            <div className="col-md-10 col-md-offset-2 file-upload-con">
              <FileUploadUtil
                onSuccess={resp => this.onUploadSuccess(resp)}
                onError={err => this.onUploadError(err)} />
            </div>
          </div>
          <div className="form-group">
            <label className="col-md-2 control-label">商品详情</label>
            <div className="col-md-10">
              <RichEditor defaultDetail={this.state.defaultDetail} detail={this.state.detail} onValueChange={value => this.onDetailValueChange(value)} />
            </div>
          </div>
          <div className="form-group">
            <div className="col-md-offset-2 col-md-10">
              <button type="submit" className="btn btn-primary" onClick={e => this.onSubmit(e)}>提交</button>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
export default ProductSave;